package com.bj58.ecdata.dashboard.controllers;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bj58.ecdata.calc.dbservice.service.BusslineEnum;
import com.bj58.ecdata.calc.dbservice.service.PlatformEnum;
import com.bj58.ecdata.dashboard.cache.ServiceBeanFactory;
import com.bj58.ecdata.dashboard.constant.EnumCate;
import com.bj58.ecdata.dashboard.databll.PriviledgeBLL;
import com.bj58.ecdata.dashboard.databll.RealTimeABTestBLL;
import com.bj58.ecdata.dashboard.databll.TrackServiceBLL;
import com.bj58.ecdata.dashboard.dbentity.ABTestDict;
import com.bj58.ecdata.dashboard.dbentity.SpecialDict;
import com.bj58.ecdata.dashboard.dbentity.URLDict;
import com.bj58.ecdata.dashboard.service.AbstractBaseService;
import com.bj58.ecdata.dashboard.service.SCFClient;
import com.bj58.ecdata.dashboard.utils.DDateUtils;
import com.bj58.ecdata.dashboard.utils.DateUtil;
import com.bj58.ecdata.dashboard.utils.Option;
import com.bj58.ecdata.dashboard.utils.VelocityTools;
import com.bj58.groupbuy.action.interceptors.Check;
import com.bj58.groupbuy.action.model.User;
import com.bj58.groupbuy.action.util.MyServletRequestUtils;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.MvcController;
import com.bj58.wf.mvc.annotation.GET;
import com.bj58.wf.mvc.annotation.POST;
import com.bj58.wf.mvc.annotation.Path;

/**
 * 流量实时看板
 * 
 * @author guolu
 *
 */
@Path("/realtime")
public class NetFlowRealTimeController extends MvcController {
	private static final Log log = LogFactory.getLog(NetFlowRealTimeController.class);
	private final SomePublicUtil spu = new SomePublicUtil();
	private static final List<Option> busslineList = new ArrayList<Option>();
	private static final List<Option> platList = new ArrayList<Option>();
	private static final VelocityTools vt = new VelocityTools();
	private static AbstractBaseService<ABTestDict> abtestDict =ServiceBeanFactory.get(ABTestDict.class,null);
	private static AbstractBaseService<SpecialDict> specialDict =ServiceBeanFactory.get(SpecialDict.class,null);
	private static AbstractBaseService<URLDict> urlDict =ServiceBeanFactory.get(URLDict.class,null);
	
	{
		SCFClient.initialSCF();
		// 业务线选择
		busslineList.add(new Option("房产", "fangchan"));
		busslineList.add(new Option("黄页", "huangye"));
		busslineList.add(new Option("招聘", "zhaopin"));
		busslineList.add(new Option("二手", "ershou"));
		busslineList.add(new Option("二手车", "ershouche"));
		// 平台选择
		platList.add(new Option("PC", "PC"));
		platList.add(new Option("M", "M"));
		platList.add(new Option("APP", "APP"));
	}

	@Path("/netflow")
	@Check("dashboard/realtime/netflow")
	@POST
	@GET
	public ActionResult netFlowDashboard() {
		Map<String, Object> context = beat.getModel().getModel();
		try {
			HttpServletRequest request = beat.getRequest();
			User user = spu.getUserByCookie(request);
			// 检查业务线权限
			String[] businessOpers = PriviledgeBLL.businessOperCheck(user).split(",");
			if ("total".equals(businessOpers[0])) {
				businessOpers[0] = "";
			}
			String bussline_s = beat.getRequest().getParameter("bussline");
			String platform_s = beat.getRequest().getParameter("platform");

			BusslineEnum bussline = null;
			PlatformEnum platform = null;
			bussline = StringUtils.isBlank(bussline_s) ? null : BusslineEnum.valueOf(bussline_s);
			platform = StringUtils.isBlank(platform_s) ? null : PlatformEnum.valueOf(platform_s);

			context.put("bussline", bussline == null ? "" : bussline.value());
			context.put("platform", platform == null ? "" : platform.name());
			context.put("busslineList", businessOpers);
			context.put("business_CN_Map", EnumCate.business_CN_Map);
			context.put("platList", platList);
			context.put("vt", vt);
			// pv vppv
			JSONObject cashcost = JSONObject.fromObject(TrackServiceBLL.getDailySum(platform, bussline));
			context.put("pv", cashcost.get("pv"));
			context.put("vppv", cashcost.get("vppv"));

			return ActionResult.view("realtime/netflow");
		} catch (Exception e) {
			log.info(e);
			return ViewResult.jsonView("");
		}
	}

	
	@GET
	@Path("/netflow/netflow-uv")
	@Check("dashboard/realtime/netflow/netflow-uv")
	public ActionResult tvTrack_uv() {
//		Map<String, Object> context = beat.getModel().getModel();
		try {
			return ActionResult.view("realtime/netflow-uv");
		} catch (Exception e) {
			log.info(e);
			return ViewResult.jsonView("");
		}
	}
	
	
	@POST
	@Path("/netflow/getPvVppv")
	public ActionResult getPvVppv() {
		String bussline_s = beat.getRequest().getParameter("bussline");
		String platform_s = beat.getRequest().getParameter("platform");

		BusslineEnum bussline = null;
		PlatformEnum platform = null;
		try {
			bussline = StringUtils.isBlank(bussline_s) ? null : BusslineEnum.valueOf(bussline_s);
			platform = StringUtils.isBlank(platform_s) ? null : PlatformEnum.valueOf(platform_s);
		} catch (Exception e) {
			log.info(e);
		}
		return ViewResult.jsonView(TrackServiceBLL.getDailySum(platform, bussline));
	}

	/**
	 * 按秒获取流量数据（2秒内的数据）
	 * 
	 * @return
	 */
	@POST
	@Path("/netflow/getHourData")
	public ActionResult getCPCHourData() {
		String type_s = beat.getRequest().getParameter("type");
		String bussline_s = beat.getRequest().getParameter("bussline");
		String platform_s = beat.getRequest().getParameter("platform");
		String time_s = beat.getRequest().getParameter("time");
		try {
			BusslineEnum bussline = StringUtils.isBlank(bussline_s) ? null : BusslineEnum.valueOf(bussline_s);
			PlatformEnum platform = StringUtils.isBlank(platform_s) ? null : PlatformEnum.valueOf(platform_s);
			long time = NumberUtils.toLong(time_s, 0);

			return ViewResult.jsonpView(TrackServiceBLL.getData(type_s, platform, bussline, time));

		} catch (Exception e) {
		}

		return ViewResult.jsonView("{}");
	}

	@POST
	@Path("/netflow/getDayData")
	public ActionResult getCPCDayData() {
		String type_s = beat.getRequest().getParameter("type");
		String bussline_s = beat.getRequest().getParameter("bussline");
		String platform_s = beat.getRequest().getParameter("platform");

		try {
			BusslineEnum bussline = StringUtils.isBlank(bussline_s) ? null : BusslineEnum.valueOf(bussline_s);
			PlatformEnum platform = StringUtils.isBlank(platform_s) ? null : PlatformEnum.valueOf(platform_s);
			JSONObject yes = JSONObject.fromObject(TrackServiceBLL.getDataYesterdayHourly(type_s, platform, bussline));
			JSONObject now = JSONObject.fromObject(TrackServiceBLL.getDataTodayHourly(type_s, platform, bussline));
			now.element("yesdata", yes.get("data"));
			return ViewResult.jsonpView(now.toString());

		} catch (Exception e) {
		}
		return ViewResult.jsonView("{}");
	}

	@GET
	@Path("/netflow/tv")
	@Check("dashboard/realtime/netflow/tv")
	public ActionResult netflowtv() {
		return ActionResult.view("tv/tv-netflow");
	}

	@POST
	@Path("/netflow/getSearchWrodTopList")
	public ActionResult getSearchWrodTopList() {
		String bussline_s = beat.getRequest().getParameter("bussline");
		String platform_s = beat.getRequest().getParameter("platform");
		int num = NumberUtils.toInt(beat.getRequest().getParameter("num"), 10);

		try {
			BusslineEnum bussline = StringUtils.isBlank(bussline_s) ? null : BusslineEnum.valueOf(bussline_s);
			PlatformEnum platform = StringUtils.isBlank(platform_s) ? null : PlatformEnum.valueOf(platform_s);

			return ViewResult.jsonpView(TrackServiceBLL.getSearchWrodTopList(platform, bussline, num));

		} catch (Exception e) {
		}
		return ViewResult.jsonView("{}");
	}

	/**
	 * 按分钟获取流量数据
	 * 
	 * @return
	 */
	@POST
	@Path("/netflow/getNetFlowByMin")
	public ActionResult getNetFlowByMin() {
		String type_s = beat.getRequest().getParameter("type");
		String time_s = beat.getRequest().getParameter("time");
		try {
			long time = NumberUtils.toLong(time_s, 0);
			return ViewResult.jsonpView(TrackServiceBLL.getDataTodayMinute(type_s, time));
		} catch (Exception e) {
		}

		return ViewResult.jsonView("{}");
	}

	/**
	 * 返回昨日1800个点
	 * 
	 * @return
	 */
	@POST
	@Path("/netflow/getNetFlowByMinYestoday")
	public ActionResult getNetFlowByMinYestoday() {
		String type_s = beat.getRequest().getParameter("type");
		if (StringUtils.isBlank(type_s)) {
			return ViewResult.jsonView("{}");
		}
		try {
			return ViewResult.jsonView(TrackServiceBLL.getYesTodayMinute(type_s));
		} catch (Exception e) {
		}

		return ViewResult.jsonView("{}");
	}

	
	/**
	 * 返回昨日 uv 1800个点
	 * @return
	 */
	@POST
	@Path("/netflow/getUVByMinYestoday")
	public ActionResult getUVByMinYestoday() {
		String platform_s = MyServletRequestUtils.getStringParameter(beat.getRequest(), "platform","");
		try {
			PlatformEnum platform = StringUtils.isBlank(platform_s) ? null : PlatformEnum.valueOf(platform_s);
			return ViewResult.jsonView(TrackServiceBLL.getUVYesTodayMinute(platform));
		} catch (Exception e) {
			log.error(e);
		}

		return ViewResult.jsonView("{}");
	}
	
	/**
	 * 按分钟获取流量数据
	 * @return
	 */
	@POST
	@Path("/netflow/getUVByMin")
	public ActionResult geUVByMin() {
		String platform_s = beat.getRequest().getParameter("platform");
		String time_s = beat.getRequest().getParameter("time");
		try {
			long time = NumberUtils.toLong(time_s, 0);
			time = DDateUtils.truncateToMinute(time);
			PlatformEnum platform = StringUtils.isBlank(platform_s) ? null : PlatformEnum.valueOf(platform_s);
			String rs = TrackServiceBLL.getUVDataTodayMinute(time, platform);
			return ViewResult.jsonpView(rs);
		} catch (Exception e) {
			log.error(e);
		}

		return ViewResult.jsonView("{}");
	}
	
	/**
	 * 获取总UV
	 * @return
	 */
	@POST
	@Path("/netflow/getUV")
	public ActionResult getUV() {
		try {
			String data = TrackServiceBLL.getAllUV();
			return ViewResult.jsonpView(data);
		} catch (Exception e) {
			log.error(e);
		}

		return ViewResult.jsonView("{}");
	}
	

	/**
	 * 按秒获取流量数据（2秒内的数据）
	 * 
	 * @return
	 */
	@POST
	@Path("/netflow/getUVHourData")
	public ActionResult getUVHourData() {
		String platform_s = beat.getRequest().getParameter("platform");
		String time_s = beat.getRequest().getParameter("time");
		try {
			PlatformEnum platform = StringUtils.isBlank(platform_s) ? null : PlatformEnum.valueOf(platform_s);
			long time = NumberUtils.toLong(time_s, 0);
			time = DDateUtils.truncateToMinute(time);
			return ViewResult.jsonpView(TrackServiceBLL.getUVData(platform, time));

		} catch (Exception e) {
			log.error(e);
		}

		return ViewResult.jsonView("{}");
	}

	
	/**
	 * AB测实时数据15分钟级
	 * @return
	 */
	@Path("/netflow/ab_test")
	@Check("dashboard/realtime/netflow/ab_test")
	@POST
	@GET
	public ActionResult netFlowABTest() {
		Map<String, Object> context = beat.getModel().getModel();
		try {
			HttpServletRequest request = beat.getRequest();
			User user = spu.getUserByCookie(request);
			// 检查业务线权限
			String[] businessOpers = PriviledgeBLL.businessOperCheck(user).split(",");
			if ("total".equals(businessOpers[0])) {
				businessOpers[0] = "";
			}
			String bussline_s = beat.getRequest().getParameter("bussline");
			BusslineEnum bussline = StringUtils.isBlank(bussline_s) ? null : BusslineEnum.valueOf(bussline_s);
			List<ABTestDict> versionList =  abtestDict.getListByConditon(null, null, null);
			String stat_date = MyServletRequestUtils.getStringParameter(request, "stat_date","");
			String platform = MyServletRequestUtils.getStringParameter(request, "platform","");
			String page_type = MyServletRequestUtils.getStringParameter(request, "page_type","");
			String identity = MyServletRequestUtils.getStringParameter(request, "identity","");
			if(StringUtils.isBlank(stat_date)){
				stat_date = DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
			}
			
			context.put("bussline", bussline == null ? "" : bussline.value());
			context.put("busslineList", businessOpers);
			context.put("business_CN_Map", EnumCate.business_CN_Map);
			context.put("versionList", versionList);
			context.put("stat_date", stat_date);
			context.put("platform", platform);
			context.put("page_type", page_type);
			context.put("identity", identity);
			return ActionResult.view("realtime/realtime_ab_test");
		} catch (Exception e) {
			log.info(e);
			return ViewResult.jsonView("");
		}
	}

	
	@POST
	@Path("/netflow_ab_test/getDayData")
	public ActionResult getABDayData() {
		HttpServletRequest request = beat.getRequest();
		String stat_date = MyServletRequestUtils.getStringParameter(request, "stat_date","");
		String businessName = MyServletRequestUtils.getStringParameter(request, "bussline","");
		if(StringUtils.isBlank(businessName)){
			businessName="all";
		}
		String platform = MyServletRequestUtils.getStringParameter(request, "platform","");
		String page_type = MyServletRequestUtils.getStringParameter(request, "page_type","");
		String index_type = MyServletRequestUtils.getStringParameter(request, "index_type","");
		String identity = MyServletRequestUtils.getStringParameter(request, "identity","");
		try {
			JSONObject rs = new JSONObject();
			String now = DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
			if(StringUtils.isBlank(stat_date)){
				stat_date = now;
			}
			List<Object> dataList = RealTimeABTestBLL.getDaySumData(businessName, platform, page_type, index_type, identity, stat_date);
			rs.put("data", dataList);
			
			return ViewResult.jsonpView(rs.toString());

		} catch (Exception e) {
			log.error(e);
		}
		return ViewResult.jsonView("{}");
	}


	/**
	 * special实时数据15分钟级
	 * @return
	 */
	@Path("/netflow/special")
	@Check("dashboard/realtime/netflow/special")
	@POST
	@GET
	public ActionResult netFlowSpecialTest() {
		Map<String, Object> context = beat.getModel().getModel();
		try {
			HttpServletRequest request = beat.getRequest();
			User user = spu.getUserByCookie(request);
			// 检查业务线权限
			String[] businessOpers = PriviledgeBLL.businessOperCheck(user).split(",");
			if ("total".equals(businessOpers[0])) {
				businessOpers[0] = "";
			}
			String bussline_s = beat.getRequest().getParameter("bussline");
			BusslineEnum bussline = StringUtils.isBlank(bussline_s) ? null : BusslineEnum.valueOf(bussline_s);
			List<SpecialDict> versionList =  specialDict.getListByConditon(null, null, null);
			String stat_date = MyServletRequestUtils.getStringParameter(request, "stat_date","");
			String platform = MyServletRequestUtils.getStringParameter(request, "platform","");
			String page_type = MyServletRequestUtils.getStringParameter(request, "page_type","");
			String identity = MyServletRequestUtils.getStringParameter(request, "identity","");
			if(StringUtils.isBlank(stat_date)){
				stat_date = DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
			}
			
			context.put("bussline", bussline == null ? "" : bussline.value());
			context.put("busslineList", businessOpers);
			context.put("business_CN_Map", EnumCate.business_CN_Map);
			context.put("versionList", versionList);
			context.put("stat_date", stat_date);
			context.put("platform", platform);
			context.put("page_type", page_type);
			context.put("identity", identity);
			return ActionResult.view("realtime/realtime_special");
		} catch (Exception e) {
			log.error(e);
			return ViewResult.jsonView("");
		}
	}

	
	@POST
	@Path("/netflow_special/getDayData")
	public ActionResult getSpecialDayData() {
		HttpServletRequest request = beat.getRequest();
		String stat_date = MyServletRequestUtils.getStringParameter(request, "stat_date","");
		String businessName = MyServletRequestUtils.getStringParameter(request, "bussline","");
		if(StringUtils.isBlank(businessName)){
			businessName="all";
		}
		String platform = MyServletRequestUtils.getStringParameter(request, "platform","");
		String page_type = MyServletRequestUtils.getStringParameter(request, "page_type","");
		String index_type = MyServletRequestUtils.getStringParameter(request, "index_type","");
		String identity = MyServletRequestUtils.getStringParameter(request, "identity","");
		try {
			JSONObject rs = new JSONObject();
			String now = DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
			if(StringUtils.isBlank(stat_date) || now.equals(stat_date)){
				stat_date = now;
				List<Object> today = RealTimeABTestBLL.getSpecialDaySumData(businessName, platform, page_type, index_type, identity, stat_date);
				rs.put("data", today);
//				String yes_date = DateUtil.strToStrBefore(stat_date,  "yyyy-MM-dd", 1);
//				List<Object> yes = RealTimeABTestBLL.getDaySumData(businessName, platform, page_type, index_type, identity, yes_date);
//				rs.put("yesdata", yes);
			}else{
				List<Object> today = RealTimeABTestBLL.getSpecialDaySumData(businessName, platform, page_type, index_type, identity, stat_date);
				rs.put("data", today);
			}
			
			return ViewResult.jsonpView(rs.toString());

		} catch (Exception e) {
			log.error(e);
		}
		return ViewResult.jsonView("{}");
	}

	/**
	 * url实时数据15分钟级
	 * @return
	 */
	@Path("/netflow/url")
	@Check("dashboard/realtime/netflow/url")
	@POST
	@GET
	public ActionResult netFlowURLTest() {
		Map<String, Object> context = beat.getModel().getModel();
		try {
			HttpServletRequest request = beat.getRequest();
			User user = spu.getUserByCookie(request);
			// 检查业务线权限
			String[] businessOpers = PriviledgeBLL.businessOperCheck(user).split(",");
			if ("total".equals(businessOpers[0])) {
				businessOpers[0] = "";
			}
			String bussline_s = beat.getRequest().getParameter("bussline");
			BusslineEnum bussline = StringUtils.isBlank(bussline_s) ? null : BusslineEnum.valueOf(bussline_s);
			List<URLDict> versionList =  urlDict.getListByConditon(null, null, null);
			String stat_date = MyServletRequestUtils.getStringParameter(request, "stat_date","");
			String platform = MyServletRequestUtils.getStringParameter(request, "platform","");
			String page_type = MyServletRequestUtils.getStringParameter(request, "page_type","");
			String identity = MyServletRequestUtils.getStringParameter(request, "identity","");
			if(StringUtils.isBlank(stat_date)){
				stat_date = DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
			}
			
			context.put("bussline", bussline == null ? "" : bussline.value());
			context.put("busslineList", businessOpers);
			context.put("business_CN_Map", EnumCate.business_CN_Map);
			context.put("versionList", versionList);
			context.put("stat_date", stat_date);
			context.put("platform", platform);
			context.put("page_type", page_type);
			context.put("identity", identity);
			return ActionResult.view("realtime/realtime_url");
		} catch (Exception e) {
			log.error(e);
			return ViewResult.jsonView("");
		}
	}

	
	@POST
	@Path("/netflow_url/getDayData")
	public ActionResult getURLDayData() {
		HttpServletRequest request = beat.getRequest();
		String stat_date = MyServletRequestUtils.getStringParameter(request, "stat_date","");
		String businessName = MyServletRequestUtils.getStringParameter(request, "bussline","");
		if(StringUtils.isBlank(businessName)){
			businessName="all";
		}
		String platform = MyServletRequestUtils.getStringParameter(request, "platform","");
		String page_type = MyServletRequestUtils.getStringParameter(request, "page_type","");
		String index_type = MyServletRequestUtils.getStringParameter(request, "index_type","");
		String identity = MyServletRequestUtils.getStringParameter(request, "identity","");
		try {
			JSONObject rs = new JSONObject();
			String now = DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
			if(StringUtils.isBlank(stat_date) || now.equals(stat_date)){
				stat_date = now;
				List<Object> today = RealTimeABTestBLL.getURLDaySumData(businessName, platform, page_type, index_type, identity, stat_date);
				rs.put("data", today);
//				String yes_date = DateUtil.strToStrBefore(stat_date,  "yyyy-MM-dd", 1);
//				List<Object> yes = RealTimeABTestBLL.getDaySumData(businessName, platform, page_type, index_type, identity, yes_date);
//				rs.put("yesdata", yes);
			}else{
				List<Object> today = RealTimeABTestBLL.getURLDaySumData(businessName, platform, page_type, index_type, identity, stat_date);
				rs.put("data", today);
			}
			
			return ViewResult.jsonpView(rs.toString());

		} catch (Exception e) {
			log.error(e);
		}
		return ViewResult.jsonView("{}");
	}

}
